package com.kawins.spring.valid.core;

import com.kawins.result.ResultTo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.ArrayList;
import java.util.List;

/**
 * @author rankai
 *         createTime 2017-10-2017/10/9 15:14
 */
@Aspect
@Component
public class BeanValidAspect {

    @Pointcut("@annotation(com.kawins.spring.valid.core.BeanValid)")
    public void BeanValidAspect() {
    }

    @Around("BeanValidAspect()")
    public Object doAround(ProceedingJoinPoint joinPoint) {
        BindingResult result;
        Object[] args = joinPoint.getArgs();
        if (args != null && args.length != 0) {
            List<MessageBean> list = new ArrayList<>(0);
            for (Object object : args) {
                if (object instanceof BindingResult) {
                    result = (BindingResult) object;
                    if (result.hasErrors()) {
                        FieldError error = result.getFieldError();
                        list.add(new MessageBean().setName(error.getField())
                                .setErrMsg(error.getDefaultMessage()));
                    }
                }
            }
            if (list.size() > 0) {
                return new ResultTo(1000, "校验失败").setData(list);
            }
        }
        Object proceed = null;
        try {
            proceed = joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return proceed;
    }
}
